package com.wangsd.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangsd.common.controller.AjaxResult;
import com.wangsd.common.controller.BaseController;
import com.wangsd.common.jwt.LoginUser;
import com.wangsd.common.jwt.TokenService;
import com.wangsd.common.utils.ServletUtils;
import com.wangsd.system.entity.SysRole;
import com.wangsd.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色Controller
 *
 * @author wsd
 * @date 2021-03-16
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "查询角色列表")
    @GetMapping("/list")
    public AjaxResult<PageInfo<SysRole>> list(SysRole sysRole) {
        Page page = PageHelper.startPage(ServletUtils.getParameterToInt("pageNum"), ServletUtils.getParameterToInt("pageSize"));
        List<SysRole> list = sysRoleService.selectSysRoleList(sysRole);
        return AjaxResult.success(getPageInfo(page, list));
    }

//    @ApiOperation(value = "导出角色列表")
//    @GetMapping("/export")
//    public AjaxResult export(SysRole sysRole) {
//        List<SysRole> list = sysRoleService.selectSysRoleList(sysRole);
//        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
//        return util.exportExcel(list, "role");
//    }

    @ApiOperation(value = "获取角色详细信息")
    @GetMapping("/{id}")
    public AjaxResult<SysRole> getInfo(@PathVariable("id") Long id) {
        SysRole sysRole = sysRoleService.selectSysRoleById(id);
        return AjaxResult.success(sysRole);
    }

    @ApiOperation(value = "新增/修改角色")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody SysRole sysRole) {
        sysRoleService.checkName(sysRole.getRoleName(), sysRole.getId());

        if (sysRole.getId() == null) {
            sysRoleService.insertSysRole(sysRole);
        } else {
            sysRoleService.updateSysRole(sysRole);
        }
        return AjaxResult.success("success");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        sysRoleService.deleteSysRoleById(id);
        return AjaxResult.success("success");
    }

    @ApiOperation(value = "获取下拉列表可展示的角色")
    @GetMapping("/optionselect")
    public AjaxResult<List<SysRole>> optionselect() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysRole> list = sysRoleService.selectRoleByUserId(loginUser.getSysUser().getId());
        return AjaxResult.success(list);
    }
}
